package app.stock.server;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import app.common.DatabaseManager;
import app.common.GlobalConstants;
import app.common.PropertyUtil;
import app.common.Util;
import app.stock.common.Account;
import app.stock.common.Constants;
import app.stock.common.Stock;
import app.stock.common.Summary;
import app.stock.common.Transaction;
import app.stock.common.TransactionTypes;
import app.stock.tools.StockCalculator;

public class StockManager {

	/********************************************************************************
	 * For Transaction
	 ********************************************************************************/
	private Transaction getTransactionFromResultSet(ResultSet rs) throws SQLException {
		Transaction tx = new Transaction();
		tx.id = rs.getInt("tx_id");
		tx.name = rs.getString("stock_name");
		tx.code = rs.getString("stock_code");
		if (tx.code == null) {
			tx.code = "";
		}
		tx.type = rs.getString("tx_type");
		tx.date = rs.getTimestamp("tx_date");
		tx.price = rs.getFloat("price");
		tx.amount = rs.getInt("amount");
		tx.sum1 = rs.getFloat("sum1");
		tx.sum2 = rs.getFloat("sum2");
		tx.shouxufei = rs.getFloat("shouxufei");
		tx.yinhuashui = rs.getFloat("yinhuashui");
		tx.guohufei = rs.getFloat("guohufei");
		tx.account = new Account();
		tx.account.name = rs.getString("account_name");
		return tx;
	}

	private void validateData(Transaction tx) {
		if (tx.type.equals(TransactionTypes.mairu) || tx.type.equals(TransactionTypes.maichu)) {
			if (Util.toFixedDigitsFloat(tx.price * tx.amount, 2).floatValue() != Util
					.toFixedDigitsFloat(-tx.sum1, 2).floatValue()) {
				throw new RuntimeException("Exception in validateData");
			}
			if (Util.toFixedDigitsFloat(tx.sum1 + tx.shouxufei + tx.yinhuashui + tx.guohufei, 2)
					.floatValue() != Util.toFixedDigitsFloat(tx.sum2, 2).floatValue()) {
				throw new RuntimeException("Exception in validateData");
			}

		} else if (tx.type.equals(TransactionTypes.honggupaixi)) {
			if (tx.price != 0 || tx.shouxufei != 0 || tx.yinhuashui != 0 || tx.guohufei != 0) {
				throw new RuntimeException("Exception in validateData");
			}
		} else {
			if (tx.price != 0 || tx.amount != 0 || tx.shouxufei != 0 || tx.yinhuashui != 0
					|| tx.guohufei != 0) {
				throw new RuntimeException("Exception in validateData");
			}
		}
	}

	public int getTransactionNum() {
		int num = 0;
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select count(*) from stock_transaction st");
			while (rs.next()) {
				num = (rs.getInt(1));
			}
			DatabaseManager.closeResource(rs, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return num;
	}

	public Transaction getTransactionByID(int id) {
		Transaction tx = new Transaction();
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "select st.* from stock_transaction st where st.tx_id=" + id;
			ResultSet rs = stmt.executeQuery(sqlStr);
			while (rs.next()) {
				tx = getTransactionFromResultSet(rs);
			}
			DatabaseManager.closeResource(rs, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tx;
	}

	public List getTransactionList(Transaction txCriteria) {
		List list = new ArrayList();
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "select st.*,"
					+ "(select sum(st2.amount) from stock_transaction st2 where st2.tx_date<=st.tx_date and st2.stock_code=st.stock_code) as chigu,"
					+ "(select sum(st2.sum2) from stock_transaction st2 where st2.tx_date<=st.tx_date) as cash "
					+ "from stock_transaction st ";
			String sqlWhereStr = "";
			// if(txCriteria == null) {
			// txCriteria = new Transaction();
			// txCriteria.type = TransactionTypes.mairu_maichu;
			// }
			if (txCriteria != null) {
				if (Util.hasValue(txCriteria.type) && !TransactionTypes.all.equals(txCriteria.type)) {
					if (TransactionTypes.mairu_maichu.equals(txCriteria.type)) {
						sqlWhereStr += " and ( st.tx_type = '" + TransactionTypes.mairu
								+ "' or st.tx_type = '" + TransactionTypes.maichu + "' )";
					} else if (TransactionTypes.zhuanru_zhuanchu.equals(txCriteria.type)) {
						sqlWhereStr += " and ( st.tx_type = '" + TransactionTypes.zhuanru
								+ "' or st.tx_type = '" + TransactionTypes.zhuanchu + "' )";
					} else {
						sqlWhereStr += " and st.tx_type = '" + txCriteria.type + "'";
					}
				}
				if (Util.hasValue(txCriteria.code)
						&& (!Constants.label_all.equals(txCriteria.code))) {
					sqlWhereStr += " and st.stock_code = '" + txCriteria.code + "'";
				}
				if (txCriteria.account != null) {
					if (Util.hasValue(txCriteria.account.name)) {
						sqlWhereStr += " and st.account_name = '" + txCriteria.account.name + "'";
					}
				}
			}
			sqlWhereStr = sqlWhereStr.replaceFirst("and", "where");
			sqlStr += sqlWhereStr + " order by st.tx_date";
			// System.out.println(sqlStr);
			ResultSet rs = stmt.executeQuery(sqlStr);
			while (rs.next()) {
				Transaction tx = getTransactionFromResultSet(rs);
				tx.currentAmount = rs.getInt("chigu");
				tx.currentCash = rs.getFloat("cash");
				if (tx.type.equals(TransactionTypes.mairu)) {
					tx.price2 = -tx.sum2 / tx.amount;
				} else if (tx.type.equals(TransactionTypes.maichu)) {
					tx.price2 = tx.sum2 / tx.amount;
				}
				this.validateData(tx);
				list.add(tx);
			}
			DatabaseManager.closeResource(rs, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public Map getTransactonMapGroupedByStock(List txList, String txType) {
		Map stockMap = new HashMap();
		if (txList == null) {
			txList = this.getTransactionList(null);
		}
		for (Iterator iterator = txList.iterator(); iterator.hasNext();) {
			Transaction tx = (Transaction) iterator.next();
			if (tx.type.equals(TransactionTypes.mairu) || tx.type.equals(TransactionTypes.maichu)
					|| tx.type.equals(TransactionTypes.honggupaixi)) {
				if (stockMap.get(tx.code) == null) {
					List list = new ArrayList();
					stockMap.put(tx.code, list);
				}
				List list = (List) stockMap.get(tx.code);
				list.add(tx);
			} else {
				if (stockMap.get(tx.type) == null) {
					List list = new ArrayList();
					stockMap.put(tx.type, list);
				}
				List list = (List) stockMap.get(tx.type);
				list.add(tx);
			}
		}
		return stockMap;
	}

	public Transaction addTransaction(Transaction tx) {
		try {
			Stock stCriteria = new Stock();
			stCriteria.code = tx.code;
			List stList = this.getStockList(stCriteria);
			if (stList == null || stList.size() == 0) {
				Stock st = new Stock();
				st.code = tx.code;
				st.name = tx.name;
				st.currentPrice = tx.price;
				this.addStock(st);
			}
			StockCalculator.caluclate(tx);
			Connection conn = DatabaseManager.getConnection();
			String sqlStr = "insert into stock_transaction "
					+ "(tx_date,tx_type,stock_code,stock_name,price,amount,sum1,sum2,shouxufei,yinhuashui,guohufei,account_name)"
					+ " values(?, '" + tx.type + "',?,'" + tx.name + "'," + tx.price + ","
					+ tx.amount + "," + tx.sum1 + "," + tx.sum2 + "," + tx.shouxufei + ","
					+ tx.yinhuashui + "," + tx.guohufei + ",'" + tx.account.name + "')";
			PreparedStatement stmt = conn.prepareStatement(sqlStr);
			stmt.setTimestamp(1, new Timestamp(tx.date.getTime()));
			if (Util.hasValue(tx.code)) {
				stmt.setString(2, tx.code);
			} else {
				stmt.setNull(2, Types.VARCHAR);
			}
			// System.out.println(sqlStr);
			int num = stmt.executeUpdate();
			System.out.println(num + " rows updated");
			DatabaseManager.closeResource(null, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tx;
	}

	public Transaction updateTransaction(Transaction tx) {
		try {
			Connection conn = DatabaseManager.getConnection();
			StockCalculator.caluclate(tx);
			String sqlStr = "update stock_transaction set";
			if (tx.type != null) {
				sqlStr += " tx_type='" + tx.type + "'";
			}
			if (Util.hasValue(tx.code)) {
				sqlStr += ", stock_code='" + tx.code + "'";
			}
			if (tx.name != null) {
				sqlStr += ", stock_name='" + tx.name + "'";
			}
			if (tx.date != null) {
				sqlStr += ", TX_DATE=?";
			}
			if (tx.amount != 0) {
				sqlStr += ", amount=" + tx.amount;
			}
			if (tx.price != 0) {
				sqlStr += ", PRICE=" + tx.price;
			}
			if (tx.sum1 != 0) {
				sqlStr += ", SUM1=" + tx.sum1;
			}
			if (tx.shouxufei != 0) {
				sqlStr += ", SHOUXUFEI=" + tx.shouxufei;
			}
			if (tx.yinhuashui != 0) {
				sqlStr += ", YINHUASHUI=" + tx.yinhuashui;
			}
			if (tx.guohufei != 0) {
				sqlStr += ", GUOHUFEI=" + tx.guohufei;
			}
			sqlStr += ", SUM2=" + tx.sum2;
			sqlStr += " where tx_id=" + tx.id;
			// System.out.println(sqlStr);
			PreparedStatement stmt = conn.prepareStatement(sqlStr);
			if (tx.date != null) {
				stmt.setTimestamp(1, new Timestamp(tx.date.getTime()));
			}
			int num = stmt.executeUpdate();
			System.out.println(num + " rows updated");
			DatabaseManager.closeResource(null, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tx;
	}

	public Transaction deleteTransaction(Transaction tx) {
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "delete from stock_transaction";
			sqlStr += " where tx_id=" + tx.id;
			// System.out.println(sqlStr);
			int num = stmt.executeUpdate(sqlStr);
			System.out.println(num + " rows updated");
			DatabaseManager.closeResource(null, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tx;
	}

	/********************************************************************************
	 * For Stock
	 ********************************************************************************/
	public List getStockList(Stock stCriteria) {
		List stList = new ArrayList();
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "select * from stock";
			if (stCriteria != null) {
				if (Util.hasValue(stCriteria.code)) {
					sqlStr += " and code='" + stCriteria.code + "'";
				}
			}
			sqlStr = sqlStr.replaceFirst("and", "where");
			// System.out.println(sqlStr);
			ResultSet rs = stmt.executeQuery(sqlStr);
			while (rs.next()) {
				Stock st = new Stock();
				st.currentPrice = rs.getFloat("price");
				st.code = rs.getString("code");
				st.name = rs.getString("name");
				stList.add(st);
			}
			DatabaseManager.closeResource(rs, stmt, conn);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stList;
	}

	public Stock addStock(Stock st) {
		try {
			if (st == null) {
				return st;
			}
			Connection conn = DatabaseManager.getConnection();
			String sqlStr = "insert into STOCK " + "(CODE,NAME,PRICE)" + " values(?,?,?)";
			PreparedStatement stmt = conn.prepareStatement(sqlStr);
			stmt.setString(1, st.code);
			stmt.setString(2, st.name);
			stmt.setFloat(3, st.currentPrice);
			// System.out.println(sqlStr);
			int num = stmt.executeUpdate();
			System.out.println(num + " rows updated");
			DatabaseManager.closeResource(null, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return st;
	}

	public void updateStockCurrrentPrice(Stock st) {
		try {
			if (st == null || !Util.hasValue(st.code)) {
				return;
			}
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "update stock set price=" + st.currentPrice + " where code='" + st.code
					+ "'";
			// System.out.println(sqlStr);
			int num = stmt.executeUpdate(sqlStr);
			System.out.println(num + " rows updated");
			DatabaseManager.closeResource(null, stmt, conn);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/********************************************************************************
	 * For Statics
	 ********************************************************************************/
	public List getStockSummaryList(Map transactionMap) {
		List list = new ArrayList();
		try {
			if (transactionMap == null) {
				transactionMap = getTransactonMapGroupedByStock(null, null);
			}
			Stock total = new Stock();
			total.code = Constants.label_summary;
			total.name = "";

			List stcokList = this.getStockList(null);
			Map stockMap = new HashMap();
			for (Iterator iterator = stcokList.iterator(); iterator.hasNext();) {
				Stock stock = (Stock) iterator.next();
				stockMap.put(stock.code, stock);
			}
			// for each stock
			for (Iterator iterator = transactionMap.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				List txList = (List) transactionMap.get(key);
				Stock stock = new Stock();
				stock.code = key;
				if (stockMap.get(stock.code) != null) {
					stock.currentPrice = ((Stock) stockMap.get(stock.code)).currentPrice;
				}
				getStockSummaryForStock(stock, txList);
				if (stock.name != null && stock.name.length() > 0) {
					total.currentAmount += stock.currentAmount;
					total.currentMarketValue += stock.currentMarketValue;
					total.thisInvestment += stock.thisInvestment;
					total.thisProfitWithoutCurrentMarketValue += stock.thisProfitWithoutCurrentMarketValue;
					total.thisProfit = total.thisProfitWithoutCurrentMarketValue
							+ total.currentMarketValue;
					if (total.thisInvestment > 0) {
						total.thisProfitRate = total.thisProfit / total.thisInvestment;
					}
					total.transactionedInvestment += stock.transactionedInvestment;
					total.transactionedProfitWithoutCurrentMarketValue += stock.transactionedProfitWithoutCurrentMarketValue;
					total.transactionedProfit += stock.transactionedProfit;
					if (total.transactionedInvestment > 0) {
						total.transactionedProfitRate = total.transactionedProfit
								/ total.transactionedInvestment;
					}
					total.stockInvestment += stock.stockInvestment;
					total.stockProfitWithoutCurrentMarketValue += stock.stockProfitWithoutCurrentMarketValue;
					total.stockProfit = total.stockProfitWithoutCurrentMarketValue
							+ total.currentMarketValue;
					if (total.stockInvestment > 0) {
						total.stockProfitRate = total.stockProfit / total.stockInvestment;
					}
				}
				list.add(stock);
			}
			Collections.sort(list);
			list.add(total);

			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Stock st = (Stock) iterator.next();
				if (total.currentMarketValue == 0) {
					st.currentMarketValueRate = 0;
				} else {
					st.currentMarketValueRate = st.currentMarketValue / total.currentMarketValue;
				}
			}

			Account acct = new Account();
			acct.profit = total.stockProfit;
			for (Iterator iterator = transactionMap.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				List txList = (List) transactionMap.get(key);
				Stock stock = new Stock();
				stock.code = key;
				getStockSummaryForStock(stock, txList);
				if (!Util.hasValue(stock.name)) {
					acct.investment += stock.stockInvestment;
				}
			}
			acct.profitRate = acct.profit / acct.investment;
			// list.add(acct);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	private Stock getStockSummaryForStock(Stock stock, List txList) {
		for (Iterator iterator = txList.iterator(); iterator.hasNext();) {
			Transaction tx = (Transaction) iterator.next();
			if (tx.type.equals(TransactionTypes.mairu)) {
				stock.name = tx.name;
				stock.currentAmount += tx.amount;
				stock.stockInvestment = stock.stockInvestment - tx.sum2;
				stock.stockProfitWithoutCurrentMarketValue = stock.stockProfitWithoutCurrentMarketValue
						+ tx.sum2;
			} else if (tx.type.equals(TransactionTypes.maichu)) {
				stock.name = tx.name;
				stock.currentAmount += tx.amount;
				stock.stockInvestment = stock.stockInvestment - tx.yinhuashui - tx.guohufei
						- tx.shouxufei;
				stock.stockProfitWithoutCurrentMarketValue = stock.stockProfitWithoutCurrentMarketValue
						+ tx.sum2;
			} else if (tx.type.equals(TransactionTypes.honggupaixi)) {
				stock.name = tx.name;
				stock.currentAmount += tx.amount;
				stock.stockInvestment = stock.stockInvestment + tx.sum2;
				stock.stockProfitWithoutCurrentMarketValue = stock.stockProfitWithoutCurrentMarketValue
						+ tx.sum2;
			} else if (tx.type.equals(TransactionTypes.zhuanru)) {
				stock.name = "";
				stock.stockInvestment = stock.stockInvestment + tx.sum2;
			} else if (tx.type.equals(TransactionTypes.zhuanchu)) {
				stock.name = "";
				stock.stockInvestment = stock.stockInvestment + tx.sum2;
			} else if (tx.type.equals(TransactionTypes.lixi)) {
				stock.name = "";
				stock.stockInvestment = stock.stockInvestment + tx.sum2;
			}
		}
		if (stock.currentAmount > 0) {
			stock.currentMarketValue = stock.currentPrice * stock.currentAmount;
			stock.stockBaobenPrice = -stock.stockProfitWithoutCurrentMarketValue
					/ stock.currentAmount;
		}
		stock.stockProfit = stock.stockProfitWithoutCurrentMarketValue + stock.currentMarketValue;
		stock.stockProfitRate = stock.stockProfit / stock.stockInvestment;

		// for this cycle
		List thisTxList = new ArrayList();
		if (stock.currentAmount > 0) {
			int amount = stock.currentAmount;
			int buyAmount = 0;
			for (int i = txList.size() - 1; i >= 0 && amount > 0; i--) {
				Transaction tx = (Transaction) txList.get(i);
				if (tx.type.equals(TransactionTypes.mairu)
						|| tx.type.equals(TransactionTypes.honggupaixi)) {
					amount = amount - tx.amount;
				} else if (tx.type.equals(TransactionTypes.maichu)) {
					amount = amount - tx.amount;
				}
				thisTxList.add(tx);
				if (amount == 0) {
					break;
				}
			}
			for (Iterator iterator = thisTxList.iterator(); iterator.hasNext();) {
				Transaction tx = (Transaction) iterator.next();
				if (tx.type.equals(TransactionTypes.mairu)) {
					stock.thisInvestment -= tx.sum2;
					stock.thisProfitWithoutCurrentMarketValue += tx.sum2;
					buyAmount = buyAmount + tx.amount;
				} else if (tx.type.equals(TransactionTypes.maichu)) {
					stock.thisInvestment = stock.thisInvestment - tx.yinhuashui - tx.guohufei
							- tx.shouxufei;
					stock.thisProfitWithoutCurrentMarketValue += tx.sum2;
				} else if (tx.type.equals(TransactionTypes.honggupaixi)) {
					stock.thisProfitWithoutCurrentMarketValue += tx.sum2;
					buyAmount = buyAmount + tx.amount;
				}
			}
			stock.thisInvestmentPrice = stock.thisInvestment / buyAmount;
			stock.thisBaobenPrice = -stock.thisProfitWithoutCurrentMarketValue
					/ stock.currentAmount;
			stock.thisProfit = stock.thisProfitWithoutCurrentMarketValue + stock.currentMarketValue;
			stock.thisProfitRate = stock.thisProfit / stock.thisInvestment;
		}

		// for current
		if (stock.currentAmount > 0) {
			int amount = stock.currentAmount;
			stock.currentInvestment = stock.thisInvestment;
			for (int i = 0; i < thisTxList.size(); i++) {
				Transaction tx = (Transaction) thisTxList.get(i);
				if (tx.type.equals(TransactionTypes.mairu)
						|| tx.type.equals(TransactionTypes.honggupaixi)) {
					amount = amount - tx.amount;
				}
				if (tx.type.equals(TransactionTypes.maichu)) {
					stock.currentInvestment -= tx.sum1;
				}
				/*
				 * if (amount >= 0) { stock.currentInvestment =
				 * stock.currentInvestment - tx.sum2; } else {
				 * stock.currentInvestment = stock.currentInvestment + (amount *
				 * tx.price) - tx.yinhuashui - tx.guohufei - tx.shouxufei; }
				 */
			}
			stock.currentInvestmentPrice = stock.currentInvestment / stock.currentAmount;
		}

		// for transactioned
		List transactionedTxList = new ArrayList(txList);
		if (stock.currentAmount > 0) {
			for (int i = 0; i < thisTxList.size(); i++) {
				transactionedTxList.remove(txList.size() - 1 - i);
			}
			for (Iterator iterator = transactionedTxList.iterator(); iterator.hasNext();) {
				Transaction tx = (Transaction) iterator.next();
				if (tx.type.equals(TransactionTypes.mairu)) {
					stock.transactionedInvestment -= tx.sum2;
					stock.transactionedProfit += tx.sum2;
				} else if (tx.type.equals(TransactionTypes.maichu)) {
					stock.transactionedInvestment = stock.transactionedInvestment - tx.yinhuashui
							- tx.guohufei - tx.shouxufei;
					stock.transactionedProfit += tx.sum2;
				} else if (tx.type.equals(TransactionTypes.honggupaixi)) {
					stock.transactionedProfit += tx.sum2;
				}
			}
			if (stock.transactionedInvestment > 0) {
				stock.transactionedProfitRate = stock.transactionedProfit
						/ stock.transactionedInvestment;
			}
		} else {
			stock.transactionedInvestment = stock.stockInvestment;
			stock.transactionedProfitWithoutCurrentMarketValue = stock.stockProfitWithoutCurrentMarketValue;
			stock.transactionedBaobenPrice = stock.stockBaobenPrice;
			stock.transactionedProfit = stock.stockProfit;
			stock.transactionedProfitRate = stock.stockProfitRate;
		}
		return stock;
	}

	public List sortStockSummaryList(List stockSummaryList, String columnName) {
		if (stockSummaryList == null) {
			stockSummaryList = this.getStockSummaryList(null);
		}
		if (!Util.hasValue(columnName)) {
			return stockSummaryList;
		}
		Collections.sort(stockSummaryList, new ColumnValueComparator(columnName));
		return stockSummaryList;
	}

	public Account getAccount(List stockSummaryList, List txList) {
		Account acct = new Account();
		for (int i = 0; i < txList.size(); i++) {
			Transaction tx = (Transaction) txList.get(i);
			if (tx.type.equals(TransactionTypes.zhuanru)
					|| tx.type.equals(TransactionTypes.zhuanchu)) {
				acct.investment += tx.sum2;
			}
			if (i == (txList.size() - 1)) {
				acct.cash = tx.currentCash;
			}
		}
		Stock total = (Stock) stockSummaryList.get(stockSummaryList.size() - 1);
		acct.profit = total.stockProfit;
		acct.profitRate = acct.profit / acct.investment;
		acct.marketValue = total.currentMarketValue;
		acct.asset = acct.investment + acct.profit;
		acct.asset2 = acct.cash + acct.marketValue;
		return acct;
	}

	public Summary getSummary(List txList) {
		Summary summary = new Summary();
		if (txList == null) {
			Transaction tx = new Transaction();
			tx.type = TransactionTypes.all;
			txList = this.getTransactionList(null);
		}
		summary.stockSummaryList = this.getStockSummaryList(this.getTransactonMapGroupedByStock(
				txList, null));
		summary.acct = this.getAccount(summary.stockSummaryList, txList);

		Calendar now = Calendar.getInstance();
		Calendar start = Calendar.getInstance();
		start.set(2010, 0, 28);
		Calendar between = Calendar.getInstance();
		between.setTimeInMillis((now.getTimeInMillis() - start.getTimeInMillis()));
		System.out.println((between.get(Calendar.YEAR) - 1970)
				+ (float) (between.get(Calendar.DAY_OF_YEAR)) / 365);

		return summary;
	}

	public boolean login(Account account) {
		boolean login = false;
		try {
			Connection conn = DatabaseManager.getConnection();
			Statement stmt = conn.createStatement();
			String sqlStr = "select a.* from account a where a.name='" + account.name
					+ "' and a.password='" + account.password + "'";
			ResultSet rs = stmt.executeQuery(sqlStr);
			if (rs.next()) {
				login = true;
			}
			DatabaseManager.closeResource(rs, stmt, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return login;
	}

	public static void main(String[] args) {
		System.out.println("Start......");
		PropertyUtil.put(GlobalConstants.key_appMode, GlobalConstants.value_appMode_desktop);
		GlobalConstants.listCurrent();
		DatabaseManager.init();
		StockManager mgr = new StockManager();
		List list = mgr.getStockSummaryList(mgr.getTransactonMapGroupedByStock(
				mgr.getTransactionList(null), null));
		System.out.println("list=" + list);
		DatabaseManager.shutdownDB();
	}

	class ColumnValueComparator implements Comparator {
		private final String columnName;

		public ColumnValueComparator(String columnName) {
			this.columnName = columnName;
		}

		@Override
		public int compare(Object o1, Object o2) {
			Stock st1 = (Stock) o1;
			Stock st2 = (Stock) o2;
			if (!Util.hasValue(st1.name) || !Util.hasValue(st2.name)) {
				return 0;
			}
			if (Stock.stockProfitRateName.equals(this.columnName)) {
				return Float.compare(st1.stockProfitRate, st2.stockProfitRate);
			} else if (Stock.stockProfitName.equals(this.columnName)) {
				return Float.compare(st1.stockProfit, st2.stockProfit);
			} else if (Stock.stockInvestmentName.equals(this.columnName)) {
				return Float.compare(st1.stockInvestment, st2.stockInvestment);
			} else if (Stock.transactionedProfitRateName.equals(this.columnName)) {
				return Float.compare(st1.transactionedProfitRate, st2.transactionedProfitRate);
			} else if (Stock.transactionedProfitName.equals(this.columnName)) {
				return Float.compare(st1.transactionedProfit, st2.transactionedProfit);
			} else if (Stock.transactionedInvestmentName.equals(this.columnName)) {
				return Float.compare(st1.transactionedInvestment, st2.transactionedInvestment);
			} else if (Stock.thisProfitRateName.equals(this.columnName)) {
				return Float.compare(st1.thisProfitRate, st2.thisProfitRate);
			} else if (Stock.thisProfitName.equals(this.columnName)) {
				return Float.compare(st1.thisProfit, st2.thisProfit);
			} else if (Stock.thisInvestmentName.equals(this.columnName)) {
				return Float.compare(st1.thisInvestment, st2.thisInvestment);
			}
			return 0;
		}
	}
}
